package com.ctvit.framework.web.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.ctvit.framework.web.context.ContextHolder;
import com.ctvit.sms.platform.service.MsgService;
import com.ctvit.struts.common.CommonFunc;
import com.ctvit.syn.service.SynchronizeDataService;

public class ReceiveFileServlet extends HttpServlet {
	static final String SAVE_DIR = CommonFunc.remoteFileDir;
	static final int BUFFER_SIZE = 4096;
	private Logger logger = LoggerFactory.getLogger(ReceiveFileServlet.class);
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action=request.getParameter("action");
		String reqId=request.getParameter("reqId");
		if ("exec".equals(action)){
			MsgService msgService=ContextHolder.getBean(MsgService.class);
			try {
				msgService.doExecSendMsg("'3'",reqId);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
//		String fileName = new String(request.getHeader("fileName").getBytes("ISO-8859-1"),"UTF-8");
		String fileName = new String(request.getHeader("fileName").getBytes("ISO-8859-1"),"gbk");
//		String fileName = request.getHeader("fileName");
		String noticeid=request.getHeader("noticeid");
		String isNewSite=request.getHeader("isNewSite");
		String dirString="";
		if (StringUtils.equals(isNewSite, "1")){
			dirString=SAVE_DIR+"/newsite/"+noticeid;
		}else{
			dirString=SAVE_DIR+"/"+noticeid;
		}
		File saveDire=new File(dirString);
		if (!saveDire.exists()) saveDire.mkdir();
		String extension = fileName.substring(fileName.lastIndexOf("."));
		File saveFile = new File(dirString+"/"+fileName);
//		Enumeration<String> names = request.getHeaderNames();
//		while (names.hasMoreElements()) {
//			String headerName = names.nextElement();
////			System.out.println(headerName + " = "+ request.getHeader(headerName));
//		}
		// opens input stream of the request for reading data
		InputStream inputStream = request.getInputStream();
		// opens an output stream for writing file
		FileOutputStream outputStream = new FileOutputStream(saveFile);
		byte[] buffer = new byte[BUFFER_SIZE];
		int bytesRead = -1;
		while ((bytesRead = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		outputStream.close();
		inputStream.close();
		logger.debug(fileName+" written to: " + saveFile.getAbsolutePath());
		response.getWriter().print("receive file DONE");
	}
}
